package com.starter.home.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.starter.home.domain.entity.Tags;
import com.starter.home.domain.entity.User;
import com.starter.home.service.ITagsService;
import com.starter.home.util.MyUtil;
import com.starter.home.util.ResponseResult;
import com.starter.home.util.constant.MessageConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author
 * @since 2020-05-04
 */
@RestController
@RequestMapping("/tags")
public class TagsController {
    @Autowired
    private ITagsService tagsService;

    @GetMapping(value="/getTag")
    @ResponseBody
    public ResponseResult getTags(HttpSession session){
        Optional<User> user = MyUtil.getUser(session);
        if (user.isPresent()){
            List<String> list =  tagsService.getTags(user.get().getId());
            return ResponseResult.success(list);
        }else {
            return ResponseResult.error(MessageConstant.SESSION_OUTTIME);
        }

    }
    @PostMapping(value="/save")
    @ResponseBody
    public ResponseResult save(@RequestBody Tags tags,HttpSession session){
        Optional<User> user = MyUtil.getUser(session);
        if (user.isPresent()){
            tags.setUserId(user.get().getId());
            int result =  tagsService.getBaseMapper().insert(tags);
            return result > 0 ? ResponseResult.success() : ResponseResult.error(MessageConstant.SAVE_ERROR);
        }else {
            return ResponseResult.error(MessageConstant.SESSION_OUTTIME);
        }
    }

    @PostMapping(value="/remove")
    @ResponseBody
    public ResponseResult remove(@RequestBody Tags tags,HttpSession session){
        Optional<User> user = MyUtil.getUser(session);
        if (user.isPresent()){
            tags.setUserId(user.get().getId());
            QueryWrapper<Tags> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("tag_name",tags.getTagName());
            queryWrapper.eq("user_id",user.get().getId());
            List<Tags> tags1 = tagsService.getBaseMapper().selectList(queryWrapper);
            int result = 0;
            if (tags1.size() > 0){
                result = tagsService.getBaseMapper().deleteBatchIds(tags1.stream().map(tags2 -> tags2.getId()).collect(Collectors.toSet()));
            }
            return result > 0 ? ResponseResult.success() : ResponseResult.error(MessageConstant.DELETE_ERROR);
        }else {
            return ResponseResult.error(MessageConstant.SESSION_OUTTIME);
        }
    }

}
